<template>
    <div id="goodsClass">
        <el-button type="primary" @click="addClass">添加分类</el-button>
        <el-table :data="list"  border style="width: 100%" >
            <el-table-column prop="index" label="#" width="50" >
            <!--树形菜单-->
            </el-table-column>
            <el-table-tree-column 
                file-icon="icon icon-file" 
                folder-icon="icon icon-folder" 
                prop="cat_name" 
                label="分类名称" 
                treeKey="cat_id"
                parentKey="cat_pid"
                child-key="children"
                width="500">
            </el-table-tree-column>
            <el-table-column prop="effective" label="是否有效"  width="350"></el-table-column>
            <el-table-column prop="lv" label="排序"  width="350">
                <template slot-scope="scope" >
                     <el-tag :type="scope.row.type">{{scope.row.lv}}</el-tag>
                </template>
               </el-table-column>
            <el-table-column prop="" label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" current-page.sync="10" :page-size="5"
        layout="total, prev, pager, next" :total="totalPage">
        </el-pagination>
        <!--弹出框-->
        <el-dialog title="添加分类" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
           <el-form :model="addDialog" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="动态参数" prop="name">
                    <el-input v-model="addDialog.name"></el-input>
                 </el-form-item>
                <el-form-item label="父级分类" prop="parents">   
                    <el-cascader
                        v-model="add.val"
                        @change="change"
                        :options="list1"
                        :props="{ checkStrictly: true,label:'cat_name',value:'cat_id' }"
                        clearable></el-cascader>
                </el-form-item>
           </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="sub" >确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="添加分类" :visible.sync="editDialog" width="30%" :before-close="handleClose">
           <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="动态参数" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                 </el-form-item>
           </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialog = false">取 消</el-button>
                <el-button type="primary" @click="subEdit" >确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data(){
        return {
            list:[],//全部商品数据
            list1:[],
            totalPage:0,
            pagenum:"1", //当前默认是第一页
            pagesize:5, //每页5条'
            type:"3",
            defaultProps:{
                children: 'children',
                label:'cat_name'
            },
            dialogVisible:false,
            editDialog:false,
            addDialog:{
                name:"",
                id:"" ,//分类父级的id
                lv:0 //分类层级
            },
            editForm:{
                name:"",
                id:"",
                attrId:""
            },
            add: {
                id:"",
                lv:"",
                val:""
            },
             rules: {
          name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' },
            ],
            parents:[]
            },
        }
    },
   methods: {
       //获取全部数据列表
       getData(){
           this.$http.get("categories",{
               params:{pagenum:this.pagenum,pagesize:this.pagesize},
               headers:{"Authorization":localStorage.getItem("token")}})
                .then(res=>{
                if(res.body.meta.status == 200){
                    this.list = res.body.data.result;
                    this.totalPage = res.body.data.total
                    this.list.forEach((item,i)=>{
                        item.index = i+1;
                        this.dataPro(item)
                        if(item.children){
                            item.children.forEach((item,i)=>{ 
                            this.dataPro(item)
                                if(item.children){
                                    item.children.forEach((item,i)=>{
                                    this.dataPro(item)
                                    })
                                }   
                            })
                        }
                    })
                }    
            // console.log(res.body)  
             })
        },
        //提交添加的分类
        sub(){
          //如果没有选择分类的父级 那么层级设置为0，
          //父级ID也为0
         if(!this.add.val){
              this.add.lv = 0
              this.add.id = 0
            }
        this.dialogVisible = false;
         this.$http.post("categories",
         {cat_pid:this.add.id,cat_name:this.addDialog.name,cat_level:this.add.lv},
          {headers:{"Authorization":localStorage.getItem("token")}})
          .then(res=>{
              if(res.body.meta.status == 201){
                this.$message({
                    message: '添加成功',
                    type: 'success'
                });
                this.getData()
                this.add.val ="";
                this.editForm.name = ""
                //console.log(res.body)
              }
              else{
                this.$message.error('添加失败');
              }
            })
        },
        change(val){
            switch(val.length){
                case 1: this.add.id = val[0];
                this.add.lv=1;break;
                case 2: this.add.id = val[1];
                this.add.lv=2;break;
                case 3: this.add.id = val[2];
                this.add.lv=3;break;
           }
         //console.log(this.add)
        },
        //给得到的数据统一添加一些需要用到的数据 因为子数据也需要同样的操作 所以单独封装
        dataPro(item){
             item.effective = "是";
            switch(item.cat_level){
            case 0: item.lv="一级";item.type="";break;
            case 1:item.lv="二级"; item.type="success";break;
            case 2:item.lv="三级";item.type="warning";break;
            }
        },
        //添加分类的弹窗
        addClass(){
           this.dialogVisible = true
           this.$http.get("categories",{
               params:{type:"2",pagenum:this.pagenum,pagesize:this.pagesize},
               headers:{"Authorization":localStorage.getItem("token")}})
                .then(res=>{
                    if(res.body.meta.status == 200){
                    this.list1 = res.body.data.result
                    this.list1.forEach((item,i)=>{
                        item.index = i+1;
                        this.dataPro(item)
                            if(item.children){
                                item.children.forEach((item,i)=>{
                                    this.dataPro(item)
                                    if(item.children){
                                        item.children.forEach((item,i)=>{
                                        this.dataPro(item)
                                        })
                                    }   
                                })
                            }
                        })
                    }   
                })
         },
        //编辑的弹窗
        edit(row){
            this.editDialog = true
            this.editForm.name = row.cat_name
            this.editForm.id = row.cat_id
             this.editForm.attrId = row.attr_id
        },
        //提交编辑的内容
        subEdit(){
             this.editDialog = false
             this.$http.put("categories/"+this.editForm.id,{cat_name:this.editForm.name},
             { headers:{'Authorization':localStorage.getItem('token')}} )
                .then(res=>{
                        if(res.body.meta.status == 200){
                            this.$message({
                                message: '修改成功',
                                type: 'success'
                            });
                            this.getData()
                       }
                    else{
                         this.$message.error('修改失败');
                    }
                 })
            }, 
        //删除
        del(row){
            this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            this.$http.delete("categories/"+row.cat_id,{headers:{"Authorization":localStorage.getItem("token")}})
            .then(res=>{
                if(res.body.meta.status == 200){
                    this.$message({
                    type: 'success',
                    message: '删除成功!'
                    });
                    this.getData()
                }
                else{
                    this.$message.error('删除失败');
                }
                    // console.log(res.body)
                    })
            
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
            
        },
       handleSizeChange(val) {
       // console.log(`每页 ${val} 条`);
      },
        handleCurrentChange(val) {
         this.pagenum = val;
         this.getData()
        },
      handleNodeClick(data) {
       // console.log(data);
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
        }
    },
    created() {
           this.getData()
          this.$store.commit("changeTitle",{"t1":"商品管理","t2":"参数列表"})
           // this.getData(this.addDialog.type,this.addDialog.list1)
       },
}
</script>

<style lang="scss" scoped>
    #goodsClass{
        .el-table{
            margin:20px 0
        }
    }
</style>